// pages/zhece/zhece.js
import Toast from '@vant/weapp/toast/toast';
const db = wx.cloud.database()

//
Page({

  /**
   * 页面的初始数据
   */
  data: {
    openId: '',
    user_url: '',
    user_title: '',
    checked: '',
    openId: '',
    checked: false,
    exam_time: '',
    exam_time_show: '',
    user_integration: '',
    // 弹出时间选择面板
    time_show: false,
    // 时间选择器
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },


  },

  // 光标聚焦时打开时间选择面板
  open_time_select() {
    this.setData({
      time_show: true,
    })
  },
  // 点击确定或取消时关闭选择面板
  confirm_select(res) {
    console.log(res.detail)
    var exam_time_show = this.formatDate(res.detail) //转换时间戳
    this.setData({
      time_show: false,
      exam_time: res.detail,
      exam_time_show: exam_time_show

    })
  },
  // 时间戳转换
  formatDate: function (inputTime) {
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d;
  },
  cancel_select() {
    this.setData({
      time_show: false,
    })
  },
  // 用户头像选择
  onChooseAvatar(e) {
    // 上传用户头像到存储，并换取存储路径
    var newDateTime = Date.parse(new Date())
    wx.cloud.uploadFile({
        cloudPath: 'userlog_img/' + '用户头像' + newDateTime + '-' + '.png', // 上传至云端的路径
        filePath: e.detail.avatarUrl // 小程序临时文件路径，需结合小程序相关 API 获取
      })
      .then((res) => {
        this.setData({
          user_url: res.fileID
        })
        console.log(res.fileID)
      });
  },

  // 用户点击授权登录事件，初始化用户信息
  submit: function () {

    // 2.检查谢谢完整性
    let openId = this.data.openId
    let user_title = this.data.user_title
    let user_url = this.data.user_url
    let checked = this.data.checked
    let exam_time = this.data.exam_time
    let user_integration = this.data.user_integration
    console.log(checked)
    if (user_title == '' || user_url == ''|| exam_time == '') {
      wx.showToast({
        title: '信息不能为空！',
        icon: 'error'
      })
    } else {
      if (checked != true) {
        this.agree_null()
      } else {

        //4.上传用户信息到数据库
        let openId = wx.getStorageSync('openId')
        db.collection("user").doc(openId).get()
          .then(res => {
            console.log('换取路径' + user_url)
            db.collection("user").doc(openId).update({
              data: {
                user_title: user_title,
                user_url: user_url,
                exam_time: exam_time,
                user_integration:Number( user_integration),


              }
            })
            console.log('跟新成功')
          })
          .catch(err => {
            console.log('换取路径' + user_url)
            db.collection("user").doc(openId).set({
              data: {
                user_title: user_title,
                user_url: user_url,
                exam_time: exam_time,
                user_integration: 0,
                user_type: 0,
                user_default:0,
                user_vip:[]
              }
            })
            console.log('注册成功')
          })


        //switchTab用以跳转tarbar页面


        wx.switchTab({
          url: '/pages/tabbar/index/index',
          success: function (e) {
            var page = getCurrentPages().pop();
            if (page == undefined || page == null) return;
            page.onLoad();
          }
        })
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/tabbar/index/index',
          })
          this.onLoad();
        }, 2000)
      }
    }
  },

  agree_null() {
    Toast('请先同意《用户协议》和《隐私政策》');
  },
  user_agree: function () {
    wx.navigateTo({
      url: '/pages/my/protocol/protocol',
    })
  },
  user_link: function () {
    console.log(1)
    wx.navigateTo({
      url: '/pages/my/privacy/privacy',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取openid
    let openId = wx.getStorageSync('openId')
    // console.log(openId)
    // 查询数据库中是否有用户数据
    let res = db.collection("user").doc(openId).get()
      .then(res => {
        this.setData({
          user_url: res.data.user_url,
          user_title: res.data.user_title,
          user_integration: res.data.user_integration
        })
      })
  },
  checkboxChange: function (e) {
    let val = e.detail.value
    if (val.length > 0) {
      this.setData({
        checked: true,
      })
      //   let checked = this.data.checked
      //   console.log(checked)
    } else {
      this.setData({
        checked: false,
      })
      //   let checked = this.data.checked
      //   console.log(checked)
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },




})